package com.czh.mock.providers.text.name;

import com.alibaba.fastjson.JSON;
import com.czh.mock.exceptions.FileException;
import com.czh.mock.exceptions.code.MockCodeEnum;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

/**
 * 与中文名字相关的帮助类
 */
public class MockChineseName {
    Logger logger = LoggerFactory.getLogger(MockChineseName.class);
    private final NameConfig config;

    private MockChineseName(NameConfig config) {
        this.config = config;
    }

    public static MockChineseName build(NameConfig config) {
        return new MockChineseName(config);
    }

    private CnDataConfig cnDataConfig;

    public CnDataConfig getDataConfig() {
        if (this.cnDataConfig == null) {
            try {
                this.cnDataConfig = JSON.parseObject(ClassLoader.getSystemResourceAsStream("config/name/cn.json"), CnDataConfig.class);
            } catch (IOException e) {
                logger.error("读取中文名称数据配置文件失败：", e);
                throw new FileException(MockCodeEnum.READ_DATA_CONFIG_FILE);
            }
        }
        return cnDataConfig;
    }

    public String nextName() {
        // 获取姓氏
        String surname = this.getSurname();
        // 随机选取1~3个字组成名字
        // 确定名字的长度
        // 单姓时名字最多3个字
        // 复姓时名字最多4个字
        int nameLength = RandomUtils.nextInt(
                NameConfig.EXCLUSIVE_SURNAME_MIN_LENGTH,
                NameConfig.EXCLUSIVE_SURNAME_MAX_LENGTH + 1
        );
        String name = this.getName(nameLength);
        return surname + name;
    }

    // 取姓氏
    private String getSurname() {
        // 随机选取一个姓氏
        int index = new Random().nextInt(this.getDataConfig().getFamilyNames().size());
        return this.getDataConfig().getFamilyNames().get(index);
    }

    // 取名字
    private String getName(int onlyNameLength) {
        StringBuilder sb = new StringBuilder();
        List<String> nameWordList = new ArrayList<>();
        if (!this.config.getSex()) {
            nameWordList.addAll(this.getDataConfig().getMaleNames());
            nameWordList.addAll(this.getDataConfig().getFemaleNames());
            nameWordList.addAll(this.getDataConfig().getNeutralNames());
        } else {
            if (this.config.getMale()) {
                nameWordList.addAll(this.getDataConfig().getFamilyNames());
                nameWordList.addAll(this.getDataConfig().getNeutralNames());
            } else {
                nameWordList.addAll(this.getDataConfig().getFamilyNames());
                nameWordList.addAll(this.getDataConfig().getNeutralNames());
            }
        }
        for (int i = 0; i < onlyNameLength; i++) {
            sb.append(nameWordList.get(RandomUtils.nextInt(0, nameWordList.size())));
        }
        return sb.toString();
    }
}
